// pages/Goods/Commit/index.js
var common = require("../../../public.js")
const config = require('../../../config.js')
const app = getApp();
Page({
  data: {
    radio: '1',
    isFyApp: config.isFyApp,
    selectedAddr: false,
    active: 0, //默认选中配送方式  开始根据下标0开始
    userInfo: [],
    itemId: 0,
    storeId: 0,
    cityBenefitItemFlag: false, // 市级惠民
    benefitItemFlag: false, // 省级惠民1
    storeInfo: '', //店铺详情
    goodsInfo: '', //商品详情
    totalPostType: [], //根据店铺返回的共有多少个配送方式
    postType: 1, //邮寄方式
    count: 1, //数量
    price: 0, //单价
    storePrice: '', //商品总价
    benefitCost: '', //券的金额
    totalMoney: 0, // 最后支付总价
    postage: 0, //邮费默认值
    pickUpSelfName: '', // 提货人姓名
    pickUpSelfPhone: '', // 提货人手机
    hasSelectPAmount: 0,
    hasSelectCityPAmount: 0,
    receiverName: '',
    receiverMobile: '',
    receiverAddress: '',
    bottomBtnContent: '确认提交',
    cityCouponNo: '', //市级优惠卷编号
    canCommit: false,
    invitationCode: '',
    remark: '',
    loadingCount: 0, // 记录当前请求的个数，当不为0时，会显示加载提示
    loadingSuccessCount: 0,
    //1是微信支付 2银联支付
    goldValue: '',
    showGold: false,
    counts: 0, //金豆数量
    valueGold: 0,
    Stops: false,
    cardId: '',
    max: 0,
    storePriceTwo: 0,
    arrText: [

      {
        isSelect: false,
        name: '暂不使用金豆'
      },
      {
        isSelect: false,
        name: '抵扣￥1.00最高可使用100金豆'
      },
      {
        isSelect: false,
        name: '自定义使用金豆数量'
      },
    ],
    activeIndex: 0,
    goldBean: true,
    inputNum: 0,
    value: '',
    showStoreCoupons: false,
    comL: [], //企业券
    benefitListtop: [], //惠民券
    benefitListbottom: [], //惠民券
    showBenefitCoupons: false,
    benefitPrice: 0,
    benefitPricTop: 0,
    StoPrice: 0, //企业券优惠总额
    flag: true, //控制开关
    flags: true, //控制开关
    storePriceAddress: -1,
    inputPrice: 0,
    discountCoupons: [], //惠民叠加券
    detail:{}

  },
  // 企业券确定
  ComPany_submit() {
    console.log("打印却确定", this.data.totalPreferential)
    this.setData({
      showStoreCoupons: false,

    })
    // console.log(this.data.comL, "dkdddiokdjd")
  },
  onBenefitCouponosClose() { //惠民券关闭
    // 关闭
    // 叠加券上部
    var totalTop = 0;
    for (var i = 0; i < this.data.benefitListtop.length; i++) {
      var item = this.data.benefitListtop[i]
      if (item.isSelect) {
        totalTop = totalTop + item.discountsMoney
      }
    }
    // 叠加券底部
    var totalBottom = 0;
    for (var i = 0; i < this.data.benefitListbottom.length; i++) {
      var item = this.data.benefitListbottom[i]
      if (item.isSelect) {
        totalBottom = totalBottom + item.discountsMoney
      }
    }
    for (var i = 0; i < this.data.benefitListbottom.length; i++) {
      this.data.benefitListbottom[i].isSelect = false
    }
    for (var i = 0; i < this.data.benefitListtop.length; i++) {
      this.data.benefitListtop[i].isSelect = false
    }
    this.setData({

      benefitListtop: this.data.benefitListtop,
      benefitListbottom: this.data.benefitListbottom,
      benefitPrice: 0,
      showBenefitCoupons: false,
      flag: true,
      storePrice: this.data.storePrice + totalTop + totalBottom,

    })
  },
  // 叠加券
  benefit_coup(e) {
    var that = this
    let {
      index,
      item
    } = e.currentTarget.dataset
    console.log(item, "itemitemitem")
    if (that.data.goodsInfo.price < item.exceedMoney && !item.isSelect) {
      common.showToast('商品总额不能低于满减金额')
      return
    }

    for (var i = 0; i < this.data.benefitListbottom.length; i++) {
      if (i == index) {
        this.data.benefitListbottom[i].isSelect = !this.data.benefitListbottom[i].isSelect
      }
      // console.log(this.data.benefitListbottom,"oojjjlllll")
    }
    if (!item.isSelect) {
      var benefitPricTop = this.data.benefitPrice + item.discountsMoney //单选的优惠金额
      var benefitPrice = this.data.benefitPrice + item.discountsMoney
      var storePrice = this.data.storePrice - item.discountsMoney
    } else {
      var benefitPricTop = this.data.benefitPrice - item.discountsMoney //单选的优惠金额
      var benefitPrice = this.data.benefitPrice - item.discountsMoney
      var storePrice = this.data.storePrice + item.discountsMoney
    }
    that.setData({
      benefitListbottom: this.data.benefitListbottom,
      benefitPricTop, //单选优惠券
      benefitPrice,
      storePrice
      // storePrice:storePrice>0 ? storePrice : 0.01
    })
  },
  onStoreCouponosClose() {
    console.log(this.data.comL, "关闭关闭")
    var companyTotal = 0
    for (var i = 0; i < this.data.comL.length; i++) {
      var item = this.data.comL[i]
      if (item.isSelect) {
        companyTotal = companyTotal + this.data.comL[i].discountsMoney
      }

    }
    for (var i = 0; i < this.data.comL.length; i++) {
      this.data.comL[i].isSelect = false
    }

    this.setData({

      storePrice: this.data.storePrice + companyTotal,
      StoPrice: 0,
      comL: this.data.comL,
      flags: true,
      showStoreCoupons: false,
      componyobjs: ''
    })
  },
  // 单选
  click_benefit(e) {
    var that = this
    let {
      index,
      item
    } = e.currentTarget.dataset
    // that.data.goodsInfo.price
    if (that.data.goodsInfo.price < item.exceedMoney && that.data.flag && that.data.benefitListtop.length != 1) {
      common.showToast('商品总额不能低于满减金额')
      return
    }
    if (that.data.flag && that.data.goodsInfo.price < item.exceedMoney && that.data.benefitListtop.length == 1) {
      common.showToast('商品总额不能低于满减金额')
      return
    }
    // 选中的前提下
    if (!that.data.flag && item.isSelect != true) {
      common.showToast('此为单选，请先取消选中')
      return
    }
    for (var i = 0; i < this.data.benefitListtop.length; i++) {
      if (i == index) {
        this.data.benefitListtop[i].isSelect = !this.data.benefitListtop[i].isSelect
      } else {
        this.data.benefitListtop[i].isSelect = false
      }
    }
    if (!item.isSelect) {
      var benefitPricTop = this.data.benefitPrice + item.discountsMoney //单选的优惠金额
      var benefitPrice = this.data.benefitPrice + item.discountsMoney
      var storePrice = this.data.storePrice - benefitPrice
    } else {
      var benefitPricTop = this.data.benefitPrice - item.discountsMoney //单选的优惠金额
      var benefitPrice = this.data.benefitPrice - item.discountsMoney
      var storePrice = this.data.storePrice + this.data.benefitPrice
    }
    this.setData({
      benefitListtop: this.data.benefitListtop,
      benefitPricTop, //单选优惠券
      benefitPrice,
      storePrice
      // storePrice :storePrice>0 ? storePrice : 0.01
    }, () => {
      if (this.data.benefitListtop.findIndex(targrt => targrt.isSelect == true) == -1) {
        that.setData({
          flag: true
        })
      } else {
        that.setData({
          flag: false
        })
      }
    })
  },
  // 店铺优惠券线上券
  copuStoreList() {
    var that = this
    var tempJson = {
      storeId: that.data.storeId,
      couponType: 1, //1线上券，2线下券
      token: that.data.token,
      userId: that.data.userInfo.id
    };
    common.wxRequest("/discountCoupon/getMyCouponForStoreByType", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
      console.log(res);
      if (res.status == 200) {
        var arr = []
        for (var i = 0; i < res.data.length; i++) {
          res.data[i].beginTime = common.dateFormat('yyyy-MM-dd', res.data[i].beginTime)
          res.data[i].finishTime = common.dateFormat('yyyy-MM-dd', res.data[i].finishTime)
          res.data[i].isSelect = false
          // console.log( res.data[i].exceedMoney)
          if (that.data.storePrice - res.data[i].exceedMoney > 0) {
            console.log(res.data[i].exceedMoney)
            arr.unshift(res.data[i])
          } else {
            arr.push(res.data[i])
          }

        }

        // 

        that.setData({
          comL: arr
        })
      }
    });
  },
  // 惠民券
  copuBenifitList() {
    var that = this
    var tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      itemId: that.data.itemId,
      buyNums: that.data.count,

    };
    common.wxRequest("/order/getUserCityDiscountCoupon", "post", tempJson, 'application/x-www-form-urlencoded', function (res) {
      console.log(res);
      if (res.status == 200) {
        var arr = [];
        for (var i = 0; i < res.data.length; i++) {
          res.data[i].receiveTime = common.dateFormat('yyyy-MM-dd', res.data[i].receiveTime)
          res.data[i].endTime = common.dateFormat('yyyy-MM-dd', res.data[i].endTime)
          res.data[i].isSelect = false
          if (that.data.storePrice - res.data[i].exceedMoney > 0) {
            // console.log( res.data[i].exceedMoney)
            arr.unshift(res.data[i])
          } else {
            arr.push(res.data[i])
          }
        }
        var res = arr
        // for (var i = 0; i < res.length; i++) {
        //   res[i].isSelect = false
        // }
        var benefitListtop = res.filter(item => item.isComposit == 1 || item.isComposit == null)
        var benefitListbottom = res.filter(item => item.isComposit !== 1 && item.isComposit !== null)

        that.setData({
          // comL: res,
          benefitListtop,
          benefitListbottom
        })
      }
    });
  },
  click_company(e) {
    var that = this
    let {
      index,
      item
    } = e.currentTarget.dataset
    if (that.data.goodsInfo.price < item.exceedMoney && that.data.flags && that.data.comL.length != 1) {
      common.showToast('商品总额不能低于满减金额')
      return
    }
    if (that.data.flags && that.data.goodsInfo.price < item.exceedMoney && that.data.comL.length == 1) {
      common.showToast('商品总额不能低于满减金额')
      return
    }
    if (!that.data.flags && item.isSelect != true) {
      common.showToast('此为单选，请先取消选中')
      return
    }
    for (var i = 0; i < this.data.comL.length; i++) {
      if (i == index) {
        this.data.comL[i].isSelect = !this.data.comL[i].isSelect
      } else {
        this.data.comL[i].isSelect = false
      }
    }
    if (!item.isSelect) {
      var StoPrice = this.data.StoPrice + item.discountsMoney //单选的优惠金额
      // console.log(this.data.storePrice,"StoPriceStoPriceStoPrice")
      var storePrice = this.data.storePrice.toFixed(2) - StoPrice

    } else {
      var StoPrice = this.data.StoPrice - item.discountsMoney //单选的优惠金额
      var storePrice = this.data.storePrice + this.data.StoPrice
    }
    console.log(storePrice, "storePricestorePrice")
    this.setData({
      StoPrice,
      // storePrice:storePrice > 0 ? storePrice : 0.01,
      storePrice,
      comL: this.data.comL
    }, () => {
      console.log(this.data.comL)
      var inde = this.data.comL.findIndex(t => t.isSelect == true)
      console.log(inde, "ddd")
      var coupObj = inde != -1 ? this.data.comL[inde] : ''
      console.log(coupObj, "coupObjcoupObj")
      that.setData({
        componyobjs: coupObj
      })
      if (this.data.comL.findIndex(targrt => targrt.isSelect == true) == -1) {
        that.setData({
          flags: true
        })

      } else {
        that.setData({
          flags: false
        })
      }
    })

  },
  // 企业券
  companyVoucherList() {

    this.setData({
      showStoreCoupons: true
    })
  },

  // 提交
  submit_clicks() {
    if (this.data.benefitPrice || this.data.StoPrice) {

    }

    this.setData({
      showGold: false,
      totalPreferential: this.data.totalPreferential + (this.data.counts / 100)
    })

  },
  // 金豆弹框
  goldFlag() {
    this.setData({
      showGold: true
    })
  },
  clcik_index(e) {
    console.log(e, 11111)
    var that = this
    let {
      index,
      item
    } = e.currentTarget.dataset

    this.setData({
      activeIndex: index,
      goldBean: false,
    })
    var storePrice = this.data.storePrice
    if (this.data.activeIndex == 0) {
      storePrice = parseFloat(this.data.storePrice) + (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格

      this.setData({
        counts: 0
      })
    } else if (this.data.activeIndex == 1) {
      if (this.data.arrText[1].isSelect) {
        return
      }
      this.setData({
        counts: this.data.goldToalTwo,
        value: 0
      }, () => {
        if ((this.data.storePrice) - (this.data.counts / 100) < 0) {
          common.showToast('抵扣金额不能超过付款额')
          this.setData({
            counts: 0,
            value: 0
          })
          return
        }
        storePrice = (this.data.storePrice) - (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格
        console.log(storePrice,"ffffppppp")
        this.setData({
          storePrice,
          inputPrice: storePrice
        })
      })
      // if (that.data.StoPrice || that.data.benefitPrice) {
      //   var storePrices = storePrice > 0 ? storePrice : 0.01
      //   this.setData({
      //     storePrice: storePrices,
      //     inputPrice: storePrice
      //   })
      // } else {
        this.setData({
          storePrice,
          inputPrice: storePrice
        })
      // }

    } else if (this.data.activeIndex == 2) {
      storePrice = parseFloat(this.data.storePrice) + (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格
    
      this.setData({
        counts: 0,
        value: 0
      })
      this.setData({
        storePrice,
        inputPrice: storePrice
      })
    }
    // StoPrice企业券  benefitPrice惠民券
    // var storePricess

    if ((this.data.storePrice) - (this.data.counts / 100) < 0) {
      common.showToast('抵扣金额不能超过付款额')
      return
    } else {
      for (var i = 0; i < this.data.arrText.length; i++) {
        if (this.data.activeIndex == i) {
          this.data.arrText[i].isSelect = true
        } else {
          this.data.arrText[i].isSelect = false
        }
      }
      this.setData({
        arrText: this.data.arrText
      })
    }

  },
  // 金豆弹框确定
  submitClose() {

    this.setData({
      showGold: false
    })
  },
  //购买数量  计算数量金额加
  goldNumChange(e) {
    var that = this;
    console.log(e.detail, "lfllll")
    var num;
    if (e.detail == '') {
      num = 0
    } else {
      num = parseInt(e.detail)
    }
    that.setData({
      counts: num, //金豆数量
      inputNum: num,
    }, () => {
      console.log(this.data.goldToalTwo) //金豆总数量
      if (this.data.inputPrice < this.data.inputNum / 100) {
        common.showToast("抵扣不能超过付款金额")
        that.setData({
          counts: 0, //金豆数量
          value: 0, //金豆数量
          storePrice: that.data.inputPrice
        })
        return
      } else if (this.data.goldToalTwo <= this.data.inputNum) {
        this.setData({
          value: this.data.goldToalTwo,
          inputNum: this.data.goldToalTwo,
          counts: this.data.goldToalTwo
        }, () => {
          common.showToast('已超过最高抵用')
        })
      } else if (this.data.inputNum < 0) {
        this.setData({
          value: 0,
          inputNum: 0,
          counts: 0
        }, () => {
          // common.showToast('已超过最高抵用')
        })
      }
      var goldToal = ((that.data.userAssets.totalMoney) - that.data.counts).toFixed(2)
      var storePrice = parseFloat(this.data.inputPrice.toFixed(2)) - (this.data.counts / 100) * (app.globalData.discount ? app.globalData.discount : 1) //总价格
      // if(that.data.StoPrice || that.data.benefitPrice){
      //   console.log("进来了",storePrice*100)
      //   var storePrices =  storePrice > 0 ? storePrice :0.01
      //    that.setData({
      //     storePrice:storePrices,
      //     goldToal
      //   })
      //   }else{
      console.log("出去了")
      that.setData({
        storePrice,
        goldToal
      })
      // }
    })
  },
  // 地址列表
  addressList() {
    const that = this
    const tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token
    }
    common.post('/user/ship/list', tempJson, function (res) {
      if (res.status === 200) {
        console.log(res, "55555")
        if (Array.isArray(res.data) && res.data.length) {
          let obj = res.data.find((v) => v.isDefault == 1 || res[0])
          that.setData({
            receiverName: obj.receiverName,
            receiverMobile: obj.receiverMobile,
            receiverAddress: obj.receiverAddress,
            selectedAddr: true,
            isDefault: obj.isDefault
          })
        }
      } else {
        common.showRequestErrMsg(res)

      }
    })
  },
  getUserAssets() { // 获取余额
    const that = this
    const tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token
    }
    common.post('/userDeposit/getUserAssetsGold', tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          userAssets: res.data,
          goldToal: res.data.totalMoney,
          goldToalTwo: res.data.totalMoney
        }, () => {
          var totalM = (parseFloat(that.data.goodsInfo.price) * app.globalData.discount * that.data.count)
          var gtotalNumber = (that.data.userAssets.totalMoney) //金豆总钱
          // 计算最大可使用量
          if (gtotalNumber < totalM) { // 金豆数量 小于 金额的max =金豆
            that.setData({
              max: (gtotalNumber)
            })
          } else if (gtotalNumber > totalM) { // 金豆数量 大于 金额的max =金豆
            that.setData({
              max: (totalM * 100)
            })
          } else { // 金豆数量 等于 金额的max =金豆
            that.setData({
              max: (gtotalNumber)
            })
          }
        })
      } else {
        common.showRequestErrMsg(res)
        that.setData({
          userAssets: res.data
        })
      }
    })
  },
  onClose() {
    var that = this
    // var storePrice = (parseFloat(that.data.goodsInfo.price) - that.data.counts / 100 * app.globalData.discount).toFixed(2) //总价格
    this.setData({
      showGold: false,

      // storePrice
    });
  },
  // 金豆选择
  goldBean(event) {
    this.setData({
      goldValue: '1',
    });
  },
  onChanges(event) {
    this.setData({
      radio: event.detail,
    });
  },
  onClick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      radio: name,
    });
  },
  // 惠民叠加券
  clcik_dieJia() {
    var filterArrBottom = this.data.benefitListbottom.filter(x => x.isSelect == true)
    var filterArrTop = this.data.benefitListtop.filter(x => x.isSelect == true)
    var filterArrBottomKey = []
    var obj = {}
    for (var j = 0; j < filterArrBottom.length; j++) {
      obj = {
        'couponNo': filterArrBottom[j].couponNo
      }
      filterArrBottomKey.push(obj)
    }
    // var bottomArr = []
    for (var i = 0; i < filterArrBottom.length; i++) {
      if (filterArrBottom[i].isComposit == 3 && filterArrBottom.length == 1 && (filterArrTop.length == 0 || !filterArrTop)) {
        common.showToast('叠加券不可以单独使用')
        return
      }

    }
    var youHui = this.data.totalPreferential + this.data.benefitPrice
    this.setData({
      cityCouponNo: filterArrTop.length > 0 ? filterArrTop[0].couponNo : '', //惠民券上部分
      discountCoupons: filterArrBottomKey,
      showBenefitCoupons: false,
      totalPreferential: youHui
    })
  },

  onShow() {
    console.log("onShowjinlailejjjj")
  },
  onLoad: function (options) {
    console.log(JSON.parse(options.detail),"pages/Goods/CommitBenifit/index")
    const that = this
    if (options.invitationCode) { // 是vip商品填写邀请码
      that.setData({
        invitationCode: that.options.invitationCode
      })
    }
    common.getLocalUserInfo(function (success, data) {
      console.log(data,"dataa5444444444444444")
      if (success) {
        that.setData({
          userInfo: data.user,
          token: data.token,
          openid: data.openid,
          itemId: options.itemId,
          storeId: options.storeId,
          // itemId: '7336',  //毛笔
          // storeId: '14',
          // itemId: 21523,  //一个花店
          // storeId: 5004,
          // itemId: 19205, //一个花店
          // storeId: 2182,
          detail:JSON.parse(options.detail),
          pickUpSelfName: data.user.realName,
          pickUpSelfPhone: data.user.phone,
          cardId: app.globalData.cardId,
        }, function () {
          this.setData({
            storePriceAddress: options.storePrice ? parseFloat(options.storePrice) : -1
          }, () => {
            // that.getGoodsDes() //查询商品详情信息
            // that.getShopDes() //店铺详情

          })


          if (!that.data.selectedAddr) {
            that.addressList() //地址列表
          }

          if (options.selectedAddr) {
            // 已经选择地址的逻辑，当前逻辑是从选择地址列表返回
            that.setData({
              selectedAddr: options.selectedAddr,
              receiverName: options.receiverName,
              receiverMobile: options.receiverMobile,
              receiverAddress: options.receiverAddress,
            })
          } else {
            // 默认进入 - 未选择地址，从下单页面进入
            getApp().getLocation(function (data) {
              that.data.lon = data.longitude
              that.data.lat = data.latitude
              that.setData({
                xpoint: data.longitude,
                ypoint: data.latitude
              }, function () {
                that.getPostType() //根据位置查询店铺配送方式
              })
            })
          }
        })
      }
    }, true)
  },
  inputEvent(e) {},
  //查询商品详情信息
  getGoodsDes() {
    const that = this
    let tempJson = {
      itemId: that.data.itemId
    }
    that.setData({
      loadingCount: that.data.loadingCount + 1,
      loadingSuccessCount: that.data.loadingSuccessCount - 1
    }, function () {
      common.post('/item/info', tempJson, function (res) {
        if (res.status === 200) {
          var storeprice;
          if (that.data.storePriceAddress == -1) {
            storeprice = app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount)
            that.copuStoreList()
            that.copuBenifitList()
            that.getUserAssets()
          } else {
            storeprice = that.data.storePriceAddress
          }
          that.setData({
            goodsInfo: res.data,
            cityBenefitItemFlag: res.data.cityBenefitItemFlag,
            benefitItemFlag: res.data.benefitItemFlag,
            storePrice: storeprice,
            storePriceTwo: app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount),
            price: res.data.price,
            loadingSuccessCount: that.data.loadingSuccessCount + 1
            // totalMoney:
          }, () => {
            // var isNum =     //是整数，则返回true，否则返回false
            if (typeof that.data.storePrice == 'number' && that.data.storePrice % 1 == 0) {
              that.setData({
                isNum: true
              })
            } else {
              that.setData({
                isNum: false
              })
            }

          })
        } else {
          common.showRequestErrMsg(res)
        }
      }, function () {
        that.setData({
          loadingCount: that.data.loadingCount - 1
        })
      })
    })
  },
  //查询店铺信息
  getShopDes() {
    var that = this
    let tempJson = {
      storeId: that.data.storeId
    }
    this.setData({
      loadingCount: this.data.loadingCount + 1,
      loadingSuccessCount: that.data.loadingSuccessCount - 1
    })
    common.post('/store/info', tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          storeInfo: res.data,
          loadingSuccessCount: that.data.loadingSuccessCount + 1
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        loadingCount: that.data.loadingCount - 1
      })
    })
  },
  //查询店铺配送方式
  getPostType: function () {
    var that = this
    var tempJson = {
      storeId: that.data.storeId,
      userId: that.data.userInfo.id,
      xpoint: that.data.xpoint,
      ypoint: that.data.ypoint
    }
    this.setData({
      loadingCount: this.data.loadingCount + 1,
      loadingSuccessCount: that.data.loadingSuccessCount - 1
    })
    common.post('/store/getStorePostTypeForBuyUser', tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          totalPostType: res.data,
          postType: res.data[0].feeType,
          postage: res.data[0].price ? res.data[0].price : 0,
          loadingSuccessCount: that.data.loadingSuccessCount + 1
        }, function () {
          that.selectComponent('#vanTabs').resize()
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        loadingCount: that.data.loadingCount - 1
      })
    })
  },
  //点击选中的配送方式
  onChangePostType(event) {
    let that = this
    if (!event.detail.index) {
      this.addressList()
    }
    that.setData({
      selectedAddr: false,
      receiverName: '',
      receiverMobile: '',
      receiverAddress: '',
    })
    let feeType = event.detail.name
    that.data.totalPostType.map((item, index) => {
      if (item.feeType == feeType) {
        console.log("yunxing", item.price)
        that.setData({
          postage: item.price,
          postType: item.feeType
        })
      }
    })
  },
  //购买数量  计算数量金额
  onNumChange(e) {
    var that = this;
    if (app.globalData.cardId) {
      var storePrice = parseFloat(app.globalData.productprice) * e.detail
    } else {
      var storePrice = parseFloat(that.data.goodsInfo.price) * e.detail * app.globalData.discount
    }
    that.setData({
      count: e.detail,
      storePrice: storePrice,
      storePriceTwo: storePrice
    })
  },
  voucherPayFunc() {
    var that = this
    let payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount)

    var tempJson = {
      token: that.data.token,
      payType: 0,
      invitationCode: that.data.invitationCode,
      list: [{
        order: {
          payment: payment.toFixed(2),
          userId: that.data.userInfo.id,
          postFee: that.data.postage,
          buyerMessage: that.data.remark,
          remark: that.data.remark,
          buyerNick: that.data.userInfo.userName,
          storeId: that.data.storeId,
          postType: that.data.postType, //1—商城配送;2—到店自提
          orderType: 1, //商品订单1，活动订单2
          userDiscountCouponId: that.data.componyobjs.udcId
        },
        items: [{
          itemId: that.data.itemId,
          num: that.data.count,
          title: that.data.goodsInfo.title,
          price: that.data.goodsInfo.price,
          totalFee: that.data.count * that.data.goodsInfo.price,
          picPath: that.data.userInfo.image,
        }],
        ship: {
          receiverName: that.data.receiverName || that.data.pickUpSelfName,
          receiverPhone: '', //可以为空
          receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
          receiverAddress: that.data.receiverAddress,
          receiverZip: ''
        }
      }]
    };
    tempJson.list[0].order.couponNo = that.data.hasSelectPNo
    tempJson.list[0].order.discountMoney = that.data.hasSelectPAmount
    tempJson.list[0].order.payment = tempJson.list[0].order.payment - parseInt(that.data.hasSelectPAmount);
    if (that.data.radio == 1) {
      var url = '/order/createBenefitOrder'
    } else if (that.data.radio == 2) { //银联支付
      var url = '/order/createChinaumsOrder'
    }
    common.postJson(url, tempJson, function (ret) {
      console.log("/order/createBenefitOrder接口数据为", ret);
      if (ret.status == 200) {
        console.log('惠民季创建订单跳转到的url为/pages/Goods/benefit/benefitPay/index?payBenefitMoney=' +
          ret.data[0].order.payment + '&payBenefitOrderNo=' +
          ret.data[0].order.orderNo + '&payBenefitOrderId=' + ret.data[0].order.id);
        wx.navigateTo({
          url: '/packageA/pages/Goods/benefit/benefitPay/index?payBenefitMoney=' +
            ret.data[0].order.payment + '&payBenefitOrderNo=' + ret.data[0].order.orderNo +
            '&payBenefitOrderId=' + ret.data[0].order.id + "&fromSmallProgramm=true",
        })
        return;
      } else {
        wx.showToast({
          title: ret.msg,
          icon: 'none'
        })
      }
    })
  },
  normalPayFunc() {
    // console.log( this.data.componyobjs," that.data.componyobjs.udcId")
    this.setData({
      loadingCount: this.data.loadingCount + 1
    })
    const that = this
    const payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount) // 实付金额
    // const tempJson = {
    //   token: that.data.token,
    //   invitationCode: that.data.invitationCode || '',
    //   payType: 0,
    //   cardId: that.data.cardId,
    //   list: [{
    //     order: {
    //       payment: payment.toFixed(2),
    //       userId: that.data.userInfo.id,
    //       postFee: that.data.postage, //邮费
    //       buyerMessage: that.data.remark,
    //       remark: that.data.remark,
    //       buyerNick: that.data.userInfo.userName,
    //       storeId: that.data.storeId,
    //       postType: that.data.postType, //1—商城配送;2—到店自提
    //       orderType: 1, //商品订单1，活动订单2
    //       cityCouponNo: that.data.cityCouponNo,
    //       goldPrice: that.data.counts, //金豆抵扣
    //       userDiscountCouponId: that.data.componyobjs ? that.data.componyobjs.udcId : '', //企业券线上
    //       discountCoupons: that.data.discountCoupons
    //       // discountCoupons:
    //     },
    //     items: [{
    //       itemId: that.data.itemId,
    //       num: that.data.count,
    //       title: that.data.goodsInfo.title,
    //       price: that.data.goodsInfo.price,
    //       totalFee: that.data.count * that.data.goodsInfo.price,
    //       picPath: that.data.goodsInfo.image,
    //     }],
    //     ship: {
    //       receiverName: that.data.receiverName || that.data.pickUpSelfName,
    //       receiverPhone: '', //可以为空
    //       receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
    //       receiverAddress: that.data.receiverAddress,
    //       receiverZip: ''
    //     },
    //   }]
    // };
    
     const tempJson = {
      userId:that.data.userInfo.id,
      token:that.data.token,
      cardId: that.data.cardId,
      num: that.data.count,
      couponId:that.data.detail.productId,
      storeId:that.data.detail.storeId,
    };
    console.log(payment, "paymentpayment")
    console.log(that.data.storePrice, "that.data.storePricethat.data.storePrice")
    //创建订单
    if (that.data.radio == 1) {
      var url = '/cardCoupon/createOrder'
      common.post(url, tempJson, function (ret) {
        if (ret.status == 200) {
        
          if (payment == 0 && that.data.postage == 0 && !that.data.StoPrice && !that.data.benefitPrice) {
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              success: res => {
                setTimeout(() => {
                  if (that.data.cardId) {
                    wx.navigateTo({
                      url: '/pages/ScenicArea/NianCardOrder/index?titles=2',
                    })
                  } else {
                    wx.navigateTo({
                      url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                    })
                  }
                }, 1000)
              }
            })
            return
          }
        //   var tempJson = {
        //     userId: that.data.userInfo.id,
        //     token: that.data.token,
        //     orderId: ret.data[0].order.id,
        //     openid: that.data.openid,
        //   }
  
          var tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            orderId: ret.data[0].order.id,
            xcxOpenid: that.data.openid,
          }
          that.setData({
            loadingCount: that.data.loadingCount + 1
          })
          if (that.data.radio == 1) {
            // var urls = '/wxxcxPayForGoods'
            var urls = '/wxxcxPayGoodsForChinaUms'
          } else if (that.data.radio == 2) {
            var urls = '/wxxcxPayGoodsForChinaUms'
          }
  
          common.wxPayRequest(urls, that.data.radio == 1 ? tempJson : tempJsons, function (res) {
            console.log(res, "lilili")
            if (res.status !== 200) {
              common.showRequestErrMsg(res)
            } else {
              //微信支付
              wx.requestPayment({
                'timeStamp': res.data.timeStamp,
                'nonceStr': res.data.nonceStr,
                'package': res.data.package,
                'signType': res.data.signType,
                'paySign': res.data.paySign,
                'success': function (res) {
                  common.showToast('支付成功', 'success')
                  if (that.data.cardId != '') {
                    wx.navigateTo({
                      url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                    })
                  } else {
                    wx.navigateBack({
                      delta: 1
                    })
                  }
  
                },
                'fail': function (res) {
                  if (that.data.cardId != '') {
                    wx.navigateTo({
                      url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                    })
                  } else {
                    wx.redirectTo({
                      url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                    })
                  }
  
                  if (res.errMsg === 'requestPayment:fail cancel') {} else {
                    common.showToast(res.errMsg)
                  }
                }
              })
            }
          }, function () {
            that.setData({
              loadingCount: that.data.loadingCount - 1
            })
          })
        } else {
          common.showRequestErrMsg(ret)
        }
      }, function () {
        that.setData({
          loadingCount: that.data.loadingCount - 1
        })
      })
    } else if (that.data.radio == 2) {
      var url = '/order/createChinaumsOrder'
      common.postJson(url, tempJson, function (ret) {
        if (ret.status == 200) {
        
          if (payment == 0 && that.data.postage == 0 && !that.data.StoPrice && !that.data.benefitPrice) {
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              success: res => {
                setTimeout(() => {
                  if (that.data.cardId) {
                    wx.navigateTo({
                      url: '/pages/ScenicArea/NianCardOrder/index?titles=2',
                    })
                  } else {
                    wx.navigateTo({
                      url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                    })
                  }
                }, 1000)
              }
            })
            return
          }
        //   var tempJson = {
        //     userId: that.data.userInfo.id,
        //     token: that.data.token,
        //     orderId: ret.data[0].order.id,
        //     openid: that.data.openid,
        //   }
  
          var tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            orderId: ret.data[0].order.id,
            xcxOpenid: that.data.openid,
          }
          that.setData({
            loadingCount: that.data.loadingCount + 1
          })
          if (that.data.radio == 1) {
            // var urls = '/wxxcxPayForGoods'
            var urls = '/wxxcxPayGoodsForChinaUms'
          } else if (that.data.radio == 2) {
            var urls = '/wxxcxPayGoodsForChinaUms'
          }
  
          common.wxPayRequest(urls, that.data.radio == 1 ? tempJson : tempJsons, function (res) {
            console.log(res, "lilili")
            if (res.status !== 200) {
              common.showRequestErrMsg(res)
            } else {
              //微信支付
              wx.requestPayment({
                'timeStamp': res.data.timeStamp,
                'nonceStr': res.data.nonceStr,
                'package': res.data.package,
                'signType': res.data.signType,
                'paySign': res.data.paySign,
                'success': function (res) {
                  common.showToast('支付成功', 'success')
                  if (that.data.cardId != '') {
                    wx.navigateTo({
                      url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                    })
                  } else {
                    wx.navigateBack({
                      delta: 1
                    })
                  }
  
                },
                'fail': function (res) {
                  if (that.data.cardId != '') {
                    wx.navigateTo({
                      url: '/pages/ScenicArea/NianCardOrder/index?titles=1',
                    })
                  } else {
                    wx.redirectTo({
                      url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                    })
                  }
  
                  if (res.errMsg === 'requestPayment:fail cancel') {} else {
                    common.showToast(res.errMsg)
                  }
                }
              })
            }
          }, function () {
            that.setData({
              loadingCount: that.data.loadingCount - 1
            })
          })
        } else {
          common.showRequestErrMsg(ret)
        }
      }, function () {
        that.setData({
          loadingCount: that.data.loadingCount - 1
        })
      })
    }
  
  },
  commit: common.throttleFunc(function (e) {
    if (this.data.loadingSuccessCount !== 0) {
      // 存在加载失败的接口，不进行订单提交
      // 全部加载成功loadingSuccessCount值为0
      return
    }
    const that = this
    // 自提方式，验证收货人和手机号
    if (that.data.goodsInfo.typeId == 2) {
      that.data.postType = 2
      that.data.postage = 0
    }
    console.log(that.data.postType)
    if (that.data.postType === '2' || that.data.postType === 2) {
      const name = that.data.pickUpSelfName
      if (common.isEmptyString(name)) {
        common.showToast('请输入提货人姓名')
        return
      } else if (common.isEmptyString(that.data.pickUpSelfPhone)) {
        common.showToast('请输入手机号码')
        return
      }
    }
    if (that.data.selectedAddr || that.data.postType == 2) {
      if (that.data.hasSelectPAmount) { // 省级券
        console.log('已选中惠民券');
        that.voucherPayFunc();
      } else { // 没券和市级券
        console.log('不用券||市券');
        that.normalPayFunc();
      }
    } else {
      common.showToast('您还未添加任何地址~')
    }
  }, 2000),


  jumpVoucherList() {
    this.setData({
      showBenefitCoupons: true
    })
  //   wx.navigateTo({
  //     url: '/packageA/pages/Goods/benefit/benefitVoucher/index?num=' +
  //       this.data.count + "&itemId=" +
  //       this.data.itemId +
  //       '&cityBenefitItemFlag=' +
  //       this.data.cityBenefitItemFlag +
  //       '&benefitItemFlag=' + this.data.benefitItemFlag +
  //       '&storeId=' + this.data.storeId
  //   })
  }
})